//
//  UIButton+JSCountDown.m
//  NiubilityProject
//
//  Created by Apple on 2018/3/7.
//  Copyright © 2018年 Apple. All rights reserved.
//

#import "UIButton+JSCountDown.h"

@interface UIButton ()

@property (nonatomic, assign) NSTimeInterval leaveTime;
@property (nonatomic, copy) NSString *normalTitle;
@property (nonatomic, copy) NSString *countDownFormat;
@property (nonatomic, strong) dispatch_source_t timer;
@property (nonatomic, assign) CGRect buttonOriginalFrame;
@property (nonatomic, strong) CAShapeLayer *shapeCircle;
@property (nonatomic, assign) double originaCornerRadius;


@end

@implementation UIButton (JSCountDown)

- (void)js_countDownWithTimeInterval:(NSTimeInterval)duration countDownFormat:(NSString *)format{

    if (!format){
        self.countDownFormat = @"%zd秒";
    } else {
        self.countDownFormat = format;
    }
    self.normalTitle = self.titleLabel.text;
    __block NSInteger timeOut = duration; //倒计时时间
    __weak typeof(self) weakSelf = self;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(self.timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(self.timer, ^{
        if (timeOut <= 0) { // 倒计时结束，关闭
            [weakSelf js_cancelTimer];
        } else {
            NSString *title = [NSString stringWithFormat:weakSelf.countDownFormat,timeOut];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf setTitle:title forState:UIControlStateNormal];
            });
            timeOut--;
        }
    });
    dispatch_resume(self.timer);
}


-(void)js_sleepDownWithTimeInterval:(NSTimeInterval)duration{
    
    if (!duration) {
        return;
    }
    self.userInteractionEnabled = NO;
    __block NSInteger timeOut = duration; //倒计时时间
    __weak typeof(self) weakSelf = self;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(self.timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(self.timer, ^{
        if (timeOut <= 0) { // 倒计时结束，关闭
            [weakSelf js_cancelTimer];
        } else {
            timeOut--;
            NSLog(@"按钮休眠中 剩余 %zd",timeOut);
        }
    });
    dispatch_resume(self.timer);
}
- (void)js_cancelTimer{
    
    dispatch_source_cancel(self.timer);
    self.timer = nil;
    dispatch_async(dispatch_get_main_queue(), ^{
        // 设置界面的按钮显示 根据自己需求设置
        if (self.normalTitle.length) {
            [self setTitle:self.normalTitle forState:UIControlStateNormal];
        }
        self.userInteractionEnabled = YES;
        if (self.timeStoppedCallback) { self.timeStoppedCallback(); }
    });
}
-(void)js_startLoadingAniamtion{
    self.buttonOriginalFrame = self.frame;
    self.normalTitle = self.currentTitle;
    self.originaCornerRadius = self.layer.cornerRadius;
    [self setTitle:@"" forState:UIControlStateNormal];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:0.4 animations:^{
            CGPoint center = self.center;
            //获取button高度 设置button为正方形
            CGFloat side = CGRectGetHeight(self.frame);
            
            self.frame = CGRectMake(0, 0, side, side);
            [self layoutIfNeeded];
            self.center = center;
            //削圆
            self.layer.cornerRadius = side/2;
        } completion:^(BOOL finished) {
            [self startAnimation];
        }];
    });
}
-(void)js_endLoadingAniamtion{
    [self endAnimation];
    
    [UIView animateWithDuration:0.3 animations:^{
        self.frame = self.buttonOriginalFrame;
        self.layer.cornerRadius = self.originaCornerRadius;
    } completion:^(BOOL finished) {
        [self setTitle:self.normalTitle forState:UIControlStateNormal];
    }];
}

- (void)setTimer:(dispatch_source_t)timer{
    objc_setAssociatedObject(self, @selector(timer), timer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (dispatch_source_t)timer {
    return objc_getAssociatedObject(self, _cmd);
}
- (void)setLeaveTime:(NSTimeInterval)leaveTime {
    objc_setAssociatedObject(self, @selector(leaveTime), @(leaveTime), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (void)setOriginaCornerRadius:(double)originaCornerRadius{
    objc_setAssociatedObject(self, @selector(originaCornerRadius), @(originaCornerRadius), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (double)originaCornerRadius{
   return [objc_getAssociatedObject(self, _cmd) doubleValue];
}
- (NSTimeInterval)leaveTime {
    return  [objc_getAssociatedObject(self, _cmd) doubleValue];
}
- (void)setCountDownFormat:(NSString *)countDownFormat {
    objc_setAssociatedObject(self, @selector(countDownFormat), countDownFormat, OBJC_ASSOCIATION_COPY);
}
- (NSString *)countDownFormat {
    return objc_getAssociatedObject(self, _cmd);
}
- (void)setTimeStoppedCallback:(void (^)(void))timeStoppedCallback {
    objc_setAssociatedObject(self, @selector(timeStoppedCallback), timeStoppedCallback, OBJC_ASSOCIATION_COPY);
}

- (void (^)(void))timeStoppedCallback {
    return objc_getAssociatedObject(self, _cmd);
}

- (void)setNormalTitle:(NSString *)normalTitle {
    objc_setAssociatedObject(self, @selector(normalTitle), normalTitle, OBJC_ASSOCIATION_COPY);
}

- (NSString *)normalTitle {
    return objc_getAssociatedObject(self, _cmd);
}

- (void)setButtonOriginalFrame:(CGRect)buttonOriginalFrame{
    frameModel *m = [frameModel new];
    m.x = buttonOriginalFrame.origin.x;
    m.y = buttonOriginalFrame.origin.y;
    m.w = buttonOriginalFrame.size.width;
    m.h = buttonOriginalFrame.size.height;
    objc_setAssociatedObject(self, @selector(buttonOriginalFrame), m, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (CGRect)buttonOriginalFrame{
    frameModel *m = objc_getAssociatedObject(self, _cmd);
    return CGRectMake(m.x, m.y, m.w, m.h);
}

- (void)setShapeCircle:(CAShapeLayer *)shapeCircle{
    objc_setAssociatedObject(self, @selector(shapeCircle), shapeCircle, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (CAShapeLayer *)shapeCircle{
    return objc_getAssociatedObject(self, _cmd);
}
/** 开始动画 */
-(void)startAnimation {
    
    CGFloat buttonwidth = CGRectGetHeight(self.buttonOriginalFrame);
    
    self.shapeCircle = [CAShapeLayer layer];
    self.shapeCircle.frame = CGRectMake(0, 0, buttonwidth, buttonwidth);
    
    //绘制 多半圆路劲  参数分别是： 圆心、半径、开始角度、结束角度、是否顺时针(1为顺时针)
    UIBezierPath * path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(buttonwidth/2, buttonwidth/2) radius:buttonwidth/2-8 startAngle:0 endAngle:1.8*M_PI clockwise:1];
    self.shapeCircle.path = path.CGPath;
    
    self.shapeCircle.strokeColor = [UIColor whiteColor].CGColor;
    self.shapeCircle.lineWidth = 2;
    self.shapeCircle.fillColor = [UIColor clearColor].CGColor;
    self.shapeCircle.strokeStart=0;
    self.shapeCircle.strokeEnd = 1;
    
    CABasicAnimation * animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"]; //transform.rotation.z 以z轴旋转  transform.rotation.x 以x轴旋转  transform.rotation.y 以y轴旋转
    animation.beginTime = 0; //马上开始
    animation.toValue = @(M_PI_2*80); //结束时的角度  2π * 80 角度
    animation.duration = 0.15*80; //持续时间  0.15 * 80 秒完成
    animation.repeatCount = 10000; //重复次数
    [self.shapeCircle addAnimation:animation forKey:@"circle"];
    
    [self.layer addSublayer:self.shapeCircle];
    
}

/** 结束动画 */
-(void)endAnimation {
    [self.shapeCircle removeFromSuperlayer];
}

+ (QMUIButton *)ba_uiHelper_generateDarkFilledButton
{
    QMUIButton *button                 = [[QMUIButton alloc] initWithFrame:CGRectMakeWithSize(CGSizeMake(200, 40))];
    button.adjustsImageWhenHighlighted = YES;
    button.titleLabel.font             = UIFontBoldMake(14);
    [button setTitleColor:UIColorWhite forState:UIControlStateNormal];
    button.backgroundColor             = UIColorGreen;
    button.highlightedBackgroundColor  = UIColorMake(0, 168, 255);
    button.layer.cornerRadius          = 5.0f;
    
    return button;
}

+ (QMUIButton *)ba_uiHelper_generateLightBorderedButton
{
    QMUIButton *button                 = [[QMUIButton alloc] initWithFrame:CGRectMakeWithSize(CGSizeMake(200, 40))];
    button.adjustsImageWhenHighlighted = YES;
    button.titleLabel.font             = UIFontBoldMake(14);
    [button setTitleColor:UIColorGreen forState:UIControlStateNormal];
    button.backgroundColor             = UIColorMake(235, 249, 255);
    button.highlightedBackgroundColor  = UIColorMake(211, 239, 252);
    button.layer.cornerRadius          = 5.0f;
    button.layer.borderColor           = UIColorMake(142, 219, 249).CGColor;
    button.layer.borderWidth           = 1.0f;
    button.highlightedBorderColor      = UIColorMake(0, 168, 225);
    
    return button;
}

+ (QMUIButton *)ba_uiHelper_creatButtonWithTitle:(NSString *)title
                                        selTitle:(NSString *)selTitle
                                      titleColor:(UIColor *)titleColor
                                   titleFontSize:(CGFloat)titleFontSize
                                           image:(UIImage *)image
                                        selImage:(UIImage *)selImage
                                          target:(id)target
                                        selector:(SEL)sel
{
    QMUIButton *button                 = [QMUIButton new];
    button.adjustsImageWhenHighlighted = YES;
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitle:selTitle forState:UIControlStateSelected];
    [button setImage:image forState:UIControlStateNormal];
    [button setImage:selImage forState:UIControlStateSelected];
    
    [button addTarget:target action:sel forControlEvents:UIControlEventTouchUpInside];
    
    button.titleLabel.font             = UIFontBoldMake(titleFontSize);
    [button setTitleColor:titleColor forState:UIControlStateNormal];
    
    return button;
}

+ (QMUIButton *)ba_uiHelper_creatYLButtonWithTitle:(NSString *)title
                                        titleColor:(UIColor *)titleColor
                                   backgroundColor:(UIColor *)backgroundColor
                                            target:(id)target
                                          selector:(SEL)sel
{
    QMUIButton *button = [UIButton ba_uiHelper_creatButtonWithTitle:title selTitle:nil titleColor:titleColor titleFontSize:15 image:nil selImage:nil target:target selector:sel];
    button.backgroundColor = backgroundColor;
    button.height = kBodyBtnHeight;
    
    return button;
}


@end

@implementation frameModel

@end
